package com.neuedu.shop.controller;

import java.io.IOException;
import java.io.PrintWriter;
//import java.io.PrintWriter;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.session.SqlSession;

import com.neuedu.shop.mapper.AdminMapper;
import com.neuedu.shop.pojo.Admin;
import com.neuedu.shop.service.AdminService;
import com.neuedu.shop.service.impl.AdminServiceImpl;
import com.neuedu.shop.util.MybatisUtil;
import com.neuedu.shop.util.ServletUtil;

/**
 * @author MrDCG
 * @version 创建时间：2019年9月16日 下午4:14:52
 *
 */
// * 表示所有的.do的页面
@WebServlet("*.admin")
public class AdminServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2785964590027554892L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取url地址（http://localhost:8080/servlet_test/findAll.do）
		String url = request.getRequestURL().toString();
		// 将url地址截取出需要的字段 /findAll
		String path = url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
		// 解决中文乱码
		ServletUtil.getCharacterEncoding(request, response);
		SqlSession sqlSession = MybatisUtil.getSession("mybatis-config.xml");
		AdminMapper adminMapper = sqlSession.getMapper(AdminMapper.class);
		AdminService adminService = new AdminServiceImpl(adminMapper);
		PrintWriter out = response.getWriter();
		// 创建session对象
		HttpSession session = request.getSession();
//		PrintWriter out = response.getWriter();
		// 根据获取到的字段判断调用什么方法
		if ("/findAll".equals(path)) {
			List<Admin> admins = adminService.findAll();
			// 原来使用out输出流显示table
			// 使用数据绑定的方式将admin对象绑定到request对象中
			request.setAttribute("admins", admins);
			// 获取一个转发器,转发到admin.jsp页面
			RequestDispatcher rd = request.getRequestDispatcher("admin_list.jsp");
			// 转发
			rd.forward(request, response);
		} else if ("/add".equals(path)) {
			Admin admin = new Admin();
			// 获取页面传过来的参数（通过表单的input的name属性获取）
			admin.setAdminName(request.getParameter("adminName"));
			admin.setAdminPassword(request.getParameter("adminPassword"));
			adminService.insert(admin);
			sqlSession.commit();
			// 重定向，执行完上面的操作后会重定向到findAll.admin页面
			response.sendRedirect("findAll.admin");
		} else if ("/load".equals(path)) {
			int id = Integer.parseInt(request.getParameter("id"));
			Admin admin = adminService.findById(id);
			request.setAttribute("admin", admin);
			RequestDispatcher rd = request.getRequestDispatcher("load_admin.jsp");
			rd.forward(request, response);

		} else if ("/update".equals(path)) {
			// 通过表单提交的数据获取id
			int id = Integer.parseInt(request.getParameter("id"));
			Admin admin = adminService.findById(id);
			admin.setAdminName(request.getParameter("adminName"));
			admin.setAdminPassword(request.getParameter("adminPassword"));
			adminService.update(admin);
			sqlSession.commit();
			// 重定向
			response.sendRedirect("findAll.admin");
		} else if ("/delete".equals(path)) {
			int id = Integer.parseInt(request.getParameter("id"));
			adminService.delete(id);
			sqlSession.commit();
			// 重定向
			response.sendRedirect("findAll.admin");

		} else if ("/login".equals(path)) {
			// 登录业务
			// 从前台获取登录信息
			String adminName = request.getParameter("adminName");
			String adminPassword = request.getParameter("adminPassword");
			String checkCode = request.getParameter("checkCode");
			String code = (String) session.getAttribute("checkcode");
			Admin admin = adminService.login(adminName, adminPassword);
			if (admin != null) {
				// 如果登录信息匹配成功，登录成功，跳转到index.jsp
				if (checkCode.equals(code)) {
					// 将admin对象保存在session对象中登录
					session.setAttribute("admin", admin);
					// 重定向
					response.sendRedirect("index.jsp");
				} else {
					request.setAttribute("code_msg", "验证码错误");
					request.getRequestDispatcher("login.jsp").forward(request, response);
				}
			} else {
				// 如果登录失败，携带登录失败的提示信息，转发到login.jsp,并给出提示信息
				request.setAttribute("msg", "登录失败");
				request.getRequestDispatcher("login.jsp").forward(request, response);
			}
		} else if ("/logout".equals(path)) {
			// 注销登录
			// 删除登录信息，退出登录
			session.invalidate();
			// 退出登录后重定向到登录界面
			response.sendRedirect("login.jsp");

		} else if ("/register".equals(path)) {
			Admin admin = new Admin();
			// 获取页面传过来的参数（通过表单的input的name属性获取）
			admin.setAdminName(request.getParameter("adminName"));
			admin.setAdminPassword(request.getParameter("adminPassword"));
			adminService.insert(admin);
			sqlSession.commit();
			// 重定向，执行完上面的操作后会重定向到findAll.admin页面
			response.sendRedirect("login.jsp");
		} else if ("/checkName".equals(path)) {
			String adminName = request.getParameter("adminName");
			Admin admin = adminService.findByAname(adminName);
			if (admin != null) {
				out.print("用户名已被注册");
			} else {
				out.print("用户名可用");
			}
		} else if("/userPasswordReset".equals(path)) {
			int id = Integer.parseInt(request.getParameter("id"));
			System.out.println(id);
			adminService.resetPassword(id);
			sqlSession.commit();
			response.sendRedirect("findAll.user");
		}

	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
}
